import { Inject, Injectable, Res } from '@nestjs/common';
import { FriendAddDto } from './dto/friend-add.dto';
import { PrismaService } from '../prisma/prisma.service';
import { ResultData } from '@/common/util/result';
import { FriendListDto } from './dto/friend-list.dto';
import * as dayjs from 'dayjs';

@Injectable()
export class FriendshipService {
    @Inject()
    private readonly prisma: PrismaService;
    // 好友列表
    async friendship(userId: number, friendListDto: FriendListDto) {
        const foundUser = await this.prisma.user.findUnique({
            where: {
                id: userId
            },
            include: {
                friends: true
            }
        })
        const friendList = await this.prisma.user.findMany({
            where: {
                id: {
                    in: foundUser.friends.map(item => item.friendId)
                },
                nickName: {
                    contains: friendListDto.nickName
                },
                username: {
                    contains: friendListDto.username
                }
            },
            select: {
                id: true,
                username: true,
                nickName: true,
                headPic: true
            },
            skip: (friendListDto.page - 1) * friendListDto.pageSize,
            take: friendListDto.pageSize
        })

        return ResultData.ok({
            rows: friendList,
            total: await this.prisma.user.count({
                where: {
                    id: {
                        in: foundUser.friends.map(item => item.friendId)
                    },
                    username: {
                        contains: friendListDto.username
                    },
                    nickName: {
                        contains: friendListDto.nickName
                    },
                }
            })
        }, '获取成功')
    }
    // 获取除自己和已添加好友的用户列表
    async usership(userId: number, friendListDto: FriendListDto) {
        const foundUser = await this.prisma.user.findUnique({
            where: {
                id: userId
            },
            include: {
                friends: true
            }
        })

        const friendList = await this.prisma.user.findMany({
            where: {
                id: {
                    notIn: [...foundUser.friends.map(friend => friend.friendId), userId]
                },
                nickName: {
                    contains: friendListDto.nickName
                },
                username: {
                    contains: friendListDto.username
                }
            },
            select: {
                id: true,
                username: true,
                nickName: true,
                headPic: true
            },
            skip: (friendListDto.page - 1) * friendListDto.pageSize,
            take: friendListDto.pageSize
        })

        return ResultData.ok({
            rows: friendList,
            total: await this.prisma.user.count({
                where: {
                    username: {
                        contains: friendListDto.username
                    },
                    nickName: {
                        contains: friendListDto.nickName
                    },
                }
            })
        }, '获取成功')
    }

    // 请求好友列表
    async requestList(userId: number) {
        const fromMeList = await this.prisma.friendRequest.findMany({
            where: {
                fromUserId: userId
            }
        })
        const toMeList = await this.prisma.friendRequest.findMany({
            where: {
                toUserId: userId
            }
        })
        const reslist = []
        for (let i = 0; i < fromMeList.length; i++) {
            const user = await this.prisma.user.findUnique({
                where: {
                    id: fromMeList[i].toUserId
                },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true,
                    headPic: true,
                    createTime: true
                }
            })
            fromMeList[i].createTime = dayjs(fromMeList[i].createTime).format('YYYY-MM-DD HH:mm:ss') as unknown as Date
            reslist.push({
                ...fromMeList[i],
                isFromMe: true,
                user
            })
        }
        for (let i = 0; i < toMeList.length; i++) {
            const user = await this.prisma.user.findUnique({
                where: {
                    id: toMeList[i].fromUserId
                },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true,
                    headPic: true,
                    createTime: true
                }
            })
            toMeList[i].createTime = dayjs(toMeList[i].createTime).format('YYYY-MM-DD HH:mm:ss') as unknown as Date
            reslist.push({
                ...toMeList[i],
                isFromMe: false,
                user
            })
        }
        return ResultData.ok(reslist, '获取成功')
    }
    // 添加好友
    async add(userId: number, friendAddDto: FriendAddDto) {
        if (userId === friendAddDto.friendId) {
            return ResultData.fail(400, '不能添加自己为好友')
        }
        const foundFriend = await this.prisma.friendship.findMany({
            where: {
                userId,
                friendId: friendAddDto.friendId
            }
        })
        if (foundFriend.length) {
            return ResultData.fail(400, '您已经添加过该好友')
        }
        const found = await this.prisma.friendRequest.findFirst({
            where: {
                fromUserId: userId,
                toUserId: friendAddDto.friendId
            }
        })
        if (found && found.status === 0) {
            found.reason = found.reason + '\n' + friendAddDto.reason
            await this.prisma.friendRequest.update({
                where: {
                    id: found.id
                },
                data: found
            })

        } else {
            await this.prisma.friendRequest.create({
                data: {
                    fromUserId: userId,
                    toUserId: friendAddDto.friendId,
                    reason: friendAddDto.reason,
                    status: 0
                }
            })
        }
        return ResultData.ok()
    }

    // 删除好友
    async remove(userId: number, friendId: number) {
        await this.prisma.friendship.deleteMany({
            where: {
                userId,
                friendId
            }
        })
        await this.prisma.friendship.deleteMany({
            where: {
                userId: friendId,
                friendId: userId
            }
        })
        return ResultData.ok()
    }
    // 同意请求
    async agree(userId: number, friendId: number) {
        await this.prisma.friendRequest.updateMany({
            where: {
                fromUserId: friendId,
                toUserId: userId,
                status: 0
            },
            data: {
                status: 1
            }
        })
        const meHaveFriends = await this.prisma.friendship.findFirst({
            where: {
                friendId,
                userId
            }
        })
        if (!meHaveFriends) {
            await this.prisma.friendship.create({
                data: {
                    userId,
                    friendId
                }
            })
        }
        const friendsHaveMe = await this.prisma.friendship.findFirst({
            where: {
                friendId: userId,
                userId: friendId
            }
        })
        if (!friendsHaveMe) {
            await this.prisma.friendship.create({
                data: {
                    friendId: userId,
                    userId: friendId
                }
            })
        }
        return ResultData.ok(null, '添加成功')
    }
    // 拒绝请求
    async reject(userId: number, friendId: number) {
        await this.prisma.friendRequest.updateMany({
            where: {
                fromUserId: friendId,
                toUserId: userId,
                status: 0
            },
            data: {
                status: 2
            }
        })
        return ResultData.ok(null, '拒绝成功')
    }
}
